package org.glxy.shop.service;

import org.glxy.shop.ProductRepository;
import org.glxy.shop.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    // 创建商品
    public Product createProduct(Product product) {
        // 初始化库存为0
        if (product.getInventory() == null) {
            product.setInventory(0L);
        }
        return productRepository.save(product);
    }

    // 更新商品
    public Product updateProduct(String id, Product product) {
        product.setId(id);
        return productRepository.save(product);
    }

    // 获取商品详情
    public Product getProductById(String id) {
        return productRepository.findById(id).orElse(null);
    }

    // 分页查询商品
    public Page<Product> getProducts(List<String> tags, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        if (tags != null && !tags.isEmpty()) {
            return productRepository.findByTagsIn(tags, pageable);
        } else {
            return productRepository.findAll(pageable);
        }
    }
}